package com.lagou.client;

import com.lagou.request.RpcRequest;
import com.lagou.response.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;


public class UserClientHandler  extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private RpcResponse response;
    private RpcRequest request;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        context = ctx;
    }

    /**
     * 收到服务端数据，唤醒等待线程
     */
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        response = (RpcResponse) msg;
        notify();
    }

    /**
     * 写出数据，开始等待唤醒
     */
    public synchronized Object call() throws InterruptedException {
        context.writeAndFlush(request);
        wait();
        return response;
    }

    /**
     * 设置参数
     */
    public void setRequest(RpcRequest para) {
        this.request = para;
    }

}
